<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="700px" class="project-form-dialog">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      class="modern-form"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="{{ t('pypm.project.projectName') }}" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="{{ t('pypm.project.enterProjectName') }}"
              clearable
              maxlength="100"
              show-word-limit
              class="modern-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="{{ t('pypm.project.description') }}" prop="description">
            <Editor v-model="formData.description" height="150px" class="modern-editor" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="{{ t('pypm.project.manager') }}" prop="managerId">
            <el-select
              v-model="formData.managerId"
              placeholder="{{ t('pypm.project.selectManager') }}"
              clearable
              filterable
              class="modern-select"
            >
              <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="{{ t('pypm.project.status') }}" prop="status">
            <el-select
              v-model="formData.status"
              placeholder="{{ t('pypm.project.selectStatus') }}"
              clearable
              class="modern-select"
            >
              <el-option label="{{ t('pypm.project.planning') }}" value="planning" />
              <el-option label="{{ t('pypm.project.active') }}" value="active" />
              <el-option label="{{ t('pypm.project.onHold') }}" value="onHold" />
              <el-option label="{{ t('pypm.project.completed') }}" value="completed" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="{{ t('pypm.project.startDate') }}" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="{{ t('pypm.project.selectStartDate') }}"
              class="modern-datepicker w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="{{ t('pypm.project.endDate') }}" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="{{ t('pypm.project.selectEndDate') }}"
              class="modern-datepicker w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="{{ t('pypm.project.priority') }}" prop="priority">
            <el-select
              v-model="formData.priority"
              placeholder="{{ t('pypm.project.selectPriority') }}"
              clearable
              class="modern-select"
            >
              <el-option label="{{ t('pypm.project.low') }}" value="low" />
              <el-option label="{{ t('pypm.project.medium') }}" value="medium" />
              <el-option label="{{ t('pypm.project.high') }}" value="high" />
              <el-option label="{{ t('pypm.project.critical') }}" value="critical" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="{{ t('pypm.project.progress') }}" prop="progress">
            <el-input-number
              v-model="formData.progress"
              :min="0"
              :max="100"
              placeholder="{{ t('pypm.project.enterProgress') }}"
              class="modern-input-number w-full"
            />
            <div class="progress-display mt-2">
              <el-progress
                :percentage="formData.progress || 0"
                :status="getProgressStatus(formData.progress || 0)"
                :stroke-width="6"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="{{ t('pypm.project.members') }}" prop="members">
            <div class="members-section">
              <el-button
                type="primary"
                plain
                @click="openMemberSelect"
                class="select-members-button"
              >
                <Icon icon="ep:plus" class="mr-5px" /> {{ t('pypm.project.selectProjectMembers') }}
              </el-button>
              <div v-if="selectedMembers.length > 0" class="selected-members-list">
                <div v-for="member in selectedMembers" :key="member.id" class="member-tag">
                  <el-avatar :size="24" :src="member.avatar || undefined">
                    {{ member.nickname?.charAt(0) || '?' }}
                  </el-avatar>
                  <span class="member-name">{{ member.nickname }}</span>
                  <el-select
                    v-model="member.role"
                    size="small"
                    @change="updateMemberRole(member.id, $event)"
                    class="role-select"
                  >
                    <el-option label="{{ t('pypm.project.projectManager') }}" value="projectManager" />
                    <el-option label="{{ t('pypm.project.businessOwner') }}" value="businessOwner" />
                    <el-option label="{{ t('pypm.project.technicalLead') }}" value="technicalLead" />
                    <el-option label="{{ t('pypm.project.teamMember') }}" value="teamMember" />
                  </el-select>
                  <el-button
                    type="text"
                    size="small"
                    @click="removeMember(member.id)"
                    class="remove-button"
                  >
                    <Icon icon="ep:delete" />
                  </el-button>
                </div>
              </div>
              <div v-else class="no-members-tip">
                {{ t('pypm.project.noMembersSelected') }}
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-button">
          {{ t('action.cancel') }}
        </el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" class="submit-button">
          {{ t('action.confirm') }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProjectApi, ProjectVO, ProjectMemberVO } from '@/api/pypm/project'
import * as UserApi from '@/api/system/user'
import UserSelectForm from '@/components/UserSelectForm/index.vue'

/** 项目信息 表单 */
defineOptions({ name: 'ProjectForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref
const userList = ref<any[]>([]) // 用户列表
const selectedMembers = ref<any[]>([]) // 选中的项目成员
const memberSelectRef = ref() // 成员选择组件引用

// 扩展表单数据类型
interface ExtendedProjectForm {
  id?: number
  name?: string
  description?: string
  startDate?: string
  endDate?: string
  state?: string
  available?: string
  managerId?: number
  manager?: any
  members?: ProjectMemberVO[]
  progress?: number
  priority?: string
  status?: string
  createTime?: string
  createBy?: string
  updateTime?: string
  updateBy?: string
}

const formData = ref<ExtendedProjectForm>({
  id: undefined,
  name: undefined,
  description: undefined,
  startDate: undefined,
  endDate: undefined,
  state: undefined,
  available: '1',
  managerId: undefined,
  manager: undefined,
  members: [],
  progress: 0,
  priority: 'medium',
  status: 'planning',
  createTime: undefined,
  createBy: undefined,
  updateTime: undefined,
  updateBy: undefined
})

// 表单校验规则
const formRules = reactive({
  name: [
    { required: true, message: t('pypm.project.projectNameRequired'), trigger: 'blur' },
    { max: 100, message: t('pypm.project.projectNameMaxLength'), trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: t('pypm.project.startDateRequired'), trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: t('pypm.project.endDateRequired'), trigger: 'blur' }
  ],
  managerId: [
    { required: true, message: t('pypm.project.managerRequired'), trigger: 'blur' }
  ],
  status: [
    { required: true, message: t('pypm.project.statusRequired'), trigger: 'blur' }
  ]
})

/** 加载用户列表 */
const loadUserList = async () => {
  try {
    userList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    console.error('加载用户列表失败:', error)
    message.error(t('sys.api.errorMessage'))
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  
  // 确保用户列表已加载
  if (userList.value.length === 0) {
    await loadUserList()
  }
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ProjectApi.getProject(id)
      
      // 转换时间格式（如果需要）
      if (data.startDate && typeof data.startDate === 'number') {
        data.startDate = new Date(data.startDate).toISOString().slice(0, 19).replace('T', ' ')
      }
      if (data.endDate && typeof data.endDate === 'number') {
        data.endDate = new Date(data.endDate).toISOString().slice(0, 19).replace('T', ' ')
      }
      
      formData.value = data as ExtendedProjectForm
      
      // 如果有负责人信息，设置 managerId
      if (data.manager) {
        formData.value.managerId = data.manager.id
      }
      
      // 处理成员数据
      if (data.members && data.members.length > 0) {
        selectedMembers.value = data.members.map((member: ProjectMemberVO) => ({
          id: member.memberId,
          nickname: member.userInfo?.nickname,
          avatar: member.userInfo?.avatar,
          role: member.role
        }))
      }
    } catch (error) {
      console.error('获取项目详情失败:', error)
      message.error(t('sys.api.errorMessage'))
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 打开成员选择器 */
const openMemberSelect = () => {
  // 排除已经选择的成员和负责人
  const excludedUserIds = new Set([formData.value.managerId])
  selectedMembers.value.forEach(member => excludedUserIds.add(member.id))
  
  if (memberSelectRef.value) {
    memberSelectRef.value.open(excludedUserIds)
  }
}

/** 处理成员选择结果 */
const handleMemberSelect = (selectedUsers: any[]) => {
  // 将新选择的用户添加到已选择列表
  selectedUsers.forEach(user => {
    // 避免重复添加
    if (!selectedMembers.value.find(m => m.id === user.id)) {
      selectedMembers.value.push({
        id: user.id,
        nickname: user.nickname,
        avatar: user.avatar,
        role: 'teamMember' // 默认角色为团队成员
      })
    }
  })
}

/** 更新成员角色 */
const updateMemberRole = (memberId: number, newRole: string) => {
  const member = selectedMembers.value.find(m => m.id === memberId)
  if (member) {
    member.role = newRole
  }
}

/** 移除成员 */
const removeMember = (memberId: number) => {
  selectedMembers.value = selectedMembers.value.filter(m => m.id !== memberId)
}

/** 获取进度条状态 */
const getProgressStatus = (progress: number): string => {
  if (progress === 100) return 'success'
  if (progress > 70) return 'primary'
  if (progress > 30) return 'warning'
  return 'info'
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 构建提交数据
    const submitData = {
      ...formData.value,
      // 转换成员数据格式
      members: selectedMembers.value.map(member => ({
        memberId: member.id,
        role: member.role
      }))
    }
    
    const data = submitData as unknown as ProjectVO
    if (formType.value === 'create') {
      await ProjectApi.createProject(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProjectApi.updateProject(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (error: any) {
    // 表单校验失败不做处理，element-plus会自动提示
    if (!error.name?.includes('Validation')) {
      message.error(error.msg || t('common.saveFail'))
    }
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    description: undefined,
    startDate: undefined,
    endDate: undefined,
    state: undefined,
    available: '1',
    managerId: undefined,
    manager: undefined,
    members: [],
    progress: 0,
    priority: 'medium',
    status: 'planning',
    createTime: undefined,
    createBy: undefined,
    updateTime: undefined,
    updateBy: undefined
  }
  selectedMembers.value = []
  formRef.value?.resetFields()
}

// 在script setup中不需要额外的template部分
</script>

<style lang="scss" scoped>
.project-form-dialog {
  .el-dialog__body {
    padding: 24px;
    max-height: 70vh;
    overflow-y: auto;
  }
  .modern-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
  .modern-input {
    border-radius: 6px;
    & .el-input__wrapper {
      border-radius: 6px;
    }
  }
  .modern-editor {
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    .w-e-toolbar {
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
    }
    .w-e-text-container {
      border-bottom-left-radius: 6px;
      border-bottom-right-radius: 6px;
    }
  }
  .modern-select {
    border-radius: 6px;
    & .el-select__wrapper {
      border-radius: 6px;
    }
  }
  .modern-datepicker {
    border-radius: 6px;
    & .el-input__wrapper {
      border-radius: 6px;
    }
  }
  .modern-input-number {
    border-radius: 6px;
    & .el-input-number__wrapper {
      border-radius: 6px;
    }
  }
  .progress-display {
    margin-top: 8px;
  }
  .members-section {
    .select-members-button {
      border-radius: 6px;
      margin-bottom: 12px;
      transition: all 0.3s ease;
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
    }
    .selected-members-list {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      max-height: 200px;
      overflow-y: auto;
      padding: 8px;
      background-color: #f9fafb;
      border-radius: 6px;
      border: 1px solid #e5e7eb;
    }
    .member-tag {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 6px 12px;
      background-color: #ffffff;
      border: 1px solid #e5e7eb;
      border-radius: 6px;
      transition: all 0.3s ease;
      &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
      }
      .member-name {
        font-size: 14px;
        color: #1f2937;
        min-width: 60px;
      }
      .role-select {
        width: 120px;
        .el-select__wrapper {
          height: 28px;
          .el-input__inner {
            height: 28px;
            font-size: 12px;
          }
        }
      }
      .remove-button {
        color: #ef4444;
        padding: 4px;
        &:hover {
          background-color: #fef2f2;
        }
      }
    }
    .no-members-tip {
      padding: 16px;
      text-align: center;
      color: #6b7280;
      background-color: #f9fafb;
      border-radius: 6px;
      border: 1px dashed #e5e7eb;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 24px 24px;
    .cancel-button {
      border-radius: 6px;
    }
    .submit-button {
      border-radius: 6px;
      transition: all 0.3s ease;
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(59, 130, 246, 0.4);
      }
    }
  }
}

// 响应式布局调整
@media screen and (max-width: 768px) {
  .project-form-dialog {
    .el-dialog {
      width: 90% !important;
      max-width: 90% !important;
    }
    .el-form-item {
      margin-bottom: 16px;
    }
    .selected-members-list {
      gap: 8px;
    }
    .member-tag {
      padding: 4px 8px;
      flex-wrap: wrap;
    }
  }
}
</style>
